using System;
using System.Collections;

namespace Tycho.Parser.Peg {
    public static class Trampoline {
        public static Yield Enumerate<T>(IEnumerable enumerable, Func<T, Yield, Yield> eachItem, Func<Yield> end) {
            return Enumerate<T> (enumerable.GetEnumerator (), eachItem, end);
        }

        private static Yield Enumerate<T>(IEnumerator enumerator, Func<T, Yield, Yield> eachItem, Func<Yield> end) {
            if (enumerator.MoveNext ()) {
                return eachItem ((T) enumerator.Current, () => Enumerate (enumerator, eachItem, end));
            } else {
                return end ();
            }
        }
    }
}